#!/usr/bin/env python

import sys
import optparse

def optional_arg(arg_default):
    def func(option,opt_str,value,parser):
        if parser.rargs and not parser.rargs[0].startswith('-'):
            val=parser.rargs[0]
            parser.rargs.pop(0)
        else:
            val=arg_default
        setattr(parser.values,option.dest,val)
    return func

def read_map(fname):
    return dict((gene_id, gene_int) for (gene_int,gene_id) in (line.split() for line in open(fname)))

def is_gene_excluded(excl_geneme_set, gene_id):
    for genome_id in excl_geneme_set:
        if gene_id.startswith(genome_id):
            return True
    return False

def main(options):
    genes_map = read_map(options.genes_map)
    genomes_map = read_map(options.genomes_map)
    excl_genomes_ids = options.excl_genomes and set(options.excl_genomes.split(',')) or set()
    for line in sys.stdin:
        gene_id, genom_id, f = line.split()
        if excl_genomes_ids and (genom_id in excl_genomes_ids or is_gene_excluded(excl_genomes_ids, gene_id)):
            pass
        else:
            sys.stdout.write("%s\t%s\t%s\n" % (genes_map[gene_id], genomes_map[genom_id], f))


if __name__ == "__main__":
    import gc
    gc.disable()

    parser = optparse.OptionParser(
        usage = 'cat results | %prog --gene-map GENES_MAP_FILE --genom-map GENOMES_MAP_FILE [--excl-genomes GENOME_ID1,GENOME_ID2 ]',
    )
    parser.add_option(
        '--genes-map',
        dest = 'genes_map',
    )
    parser.add_option(
        '--genomes-map',
        dest = 'genomes_map',
    )
    parser.add_option(
        '--excl-genomes',
        dest = 'excl_genomes',
        action = 'callback', 
        callback = optional_arg(''),
        default = '',        
    )
    options, args = parser.parse_args()

    main(options)

